package net.bluemind.ysnp.impl;

import java.util.Collections;
import java.util.List;

import net.bluemind.ysnp.ICredentialValidator;
import net.bluemind.ysnp.ICredentialValidatorFactory;
import net.bluemind.ysnp.YSNPConfiguration;
import net.bluemind.ysnp.utils.RunnableExtensionLoader;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ValidationPolicy {

	private List<ICredentialValidatorFactory> validatorsFactories;
	private Logger logger = LoggerFactory.getLogger(getClass());

	public ValidationPolicy(YSNPConfiguration conf) {
		RunnableExtensionLoader<ICredentialValidatorFactory> rel = new RunnableExtensionLoader<ICredentialValidatorFactory>();
		List<ICredentialValidatorFactory> factories = rel.loadExtensions(
				"net.bluemind.ysnp", "credentialvalidatorfactory",
				"credential_validator_factory", "implementation");

		Collections.sort(factories, new ValidatorsComparator());
		validatorsFactories = factories;
		for (ICredentialValidatorFactory cvf : validatorsFactories) {
			cvf.init(conf);
		}
	}

	public boolean validate(String login, String password, String service,
			String realm) {
		boolean valid = false;
		for (ICredentialValidatorFactory cvf : validatorsFactories) {
			ICredentialValidator validator = cvf.getValidator();
			valid = validator.validate(login, password, realm, service);
			if (valid) {
				logger.info("Access to service " + service + " granted to "
						+ login + " with '" + cvf.getName() + "' validator.");
				break;
			}
		}

		if (!valid) {
			logger.warn("all " + validatorsFactories.size()
					+ " validator(s) rejected " + login + " / " + password);
		}

		return valid;
	}
}
